package com.springBoot.springBootSysCore.common.third.pay;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;

import com.springBoot.springBootSysCore.common.third.pay.alipay.Alipay;
import com.springBoot.springBootSysCore.common.third.pay.alipay.AssistUtil;




public class AlipayUtil {
	 @Value("${projectPath}")
	private static String PROJECT_PATH;
	/**
	 * 支付宝支付
	 * @param number  订单号
	 * @param subject 商品名
	 * @param price	      价格
	 * @param notify_url	回调地址
	 * @return app调用支付宝接口可用字符串
	 * @throws Exception 
	 */
	public static String alipayPay(String number,String subject,String price,String notify_url) throws Exception{
		//创建原始参数集合
		Map<String,String> sParaTemp = Alipay.initPayParam(number, subject, price,PROJECT_PATH+"/"+notify_url);
		//签名后的参数字符串
		String rsaStr = Alipay.buildRequestParaAPP(sParaTemp);
		
		return rsaStr;
	}
	
	/**
	 * 支付宝退款
	 * @param batch_num		退款笔数
	 * @param detail_data	单笔数据集
	 * @param batch_no		批次号
	 * @param notify_url	回调地址
	 * @return
	 * @throws Exception
	 */
	public static String alipayRefund(String batch_num,String detail_data,String batch_no,String notify_url) throws Exception{
		//创建原始参数集合
		Map<String,String> sParaTemp = Alipay.initRefundParam(batch_num, detail_data,batch_no,PROJECT_PATH+"/"+notify_url);
		//签名后的参数字符串
		String rsaStr = Alipay.refund(sParaTemp);
		
		return rsaStr;
	}
	
	/**
	 * 得到支付宝回调传来的参数
	 * @param requestParams
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String,String> getAlipayParams(HttpServletRequest request){
		Map requestParams = request.getParameterMap();
		
		Map<String,String> params = new HashMap<String,String>();
		
		StringBuffer paramsStr = new StringBuffer("");
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			paramsStr.append(name+"="+valueStr+"&");
			params.put(name, valueStr);
		}
		
		System.out.println("支付宝回调函数："+paramsStr.toString());
		return params;
	}
	
	/**
	 * 验证是否是支付宝发出的请求
	 * @param params
	 * @return
	 */
	public static boolean alipayVerify(Map<String,String> params){
		return AssistUtil.verify(params);
	}
	
	/**
	 * 给支付宝回调返回状态
	 * @param response
	 * @param isOk
	 * @throws Exception 
	 */
	public static void returnState(HttpServletResponse response,boolean isOk) throws Exception{
		if(isOk){
			response.getWriter().write("success");
		}else{
			response.getWriter().write("fail");
		}
	}
	
}
